<?php
class Model_User extends Model_Base implements Zend_Acl_Role_Interface {
//   protected $_id;
//   protected $_name;
//   protected $_password;

   protected $_pk = 'id';
   protected $_fields = array(
      'id', 
      'username', 
      'password', 
      'firstname', 
      'lastname', 
      'email', 
      'address', 
      'zip', 
      'city', 
      'state', 
      'country'
   );
   protected $_table = 'users';
   protected $_name = 'users';
   
   
   public function getGroups() {

      $db = Zend_Registry::get('db');
      $sql = '
         SELECT 
            g.id, g.name
         FROM 
            groups g
            LEFT JOIN user_groups ug ON (ug.group_id = g.id)
         WHERE
            ug.user_id = ?
         GROUP BY
            g.id
      ';
      $sql1 = 'SELECT id, username
                        FROM groups
                        WHERE id = ?';

      $groups = array();
      $rows = $db->fetchAll($sql, array($this->getId()), Zend_Db::FETCH_ASSOC);
      foreach($rows as $row) {
         $group = new Model_Group();
         $group->setId($row['id']);
         $group->setName($row['name']);
         $groups[] = $group;
      }
      return $groups;
   }

   

   public static function findById($id) {
      $db = Zend_Registry::get('db');

      $sql = 'SELECT id, username, password FROM users WHERE id = ?';
      $row = $db->fetchRow($sql, array($id), Zend_Db::FETCH_ASSOC);
      if(!$row)
      return null;

      $user = new Model_User();
      $user->setId($row['id']);
//      $user->setName($row['username']);
      $user->setUserName($row['username']);
      $user->setPassword($row['password']);
      return $user;
   }
   
   public static function findByName($name) {
      $db = Zend_Registry::get('db');

      $sql = "SELECT id, username, password FROM users WHERE username LIKE '$name'";
      $row = $db->fetchRow($sql); //, array($name), Zend_Db::FETCH_BOTH );
      if(!$row)
         return null;

      $user = new Model_User();
      $user->setId($row['id']);
//      $user->setName($row['username']);
      $user->setUserName($row['username']);
      $user->setPassword($row['password']);
      return $user;
   }
   

   public function getRoleId() {
      return 'user-' . $this->id;
   }
}